<?php
namespace app\api\service;
use think\facade\{View,Session,Cache,Db};
use think\exception\HttpResponseException;
class Wxrprice
{
 
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function __construct($openId,$money,$remark)
    {   
        $basic=Db::name("wx_basic")->find(1);
        $this->appid=$basic['appid'];
        $this->out_batch_no=uniqid().time();
        $this->batch_name="佣金提现";
        $this->batch_remark=$remark;
        $this->total_amount=intval($money * 100);
        $this->openid=$openId;
        $this->apiclient_cert_path="static/efile/wxconfig/".$basic['keyfile'];
        $this->apiclient_key_path="static/efile/wxconfig/".$basic['keyfile1'];
        $this->merchant_id=$basic['mch_id'];

    }
 
    public function tixian($id){
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $pars = [];
        $pars['appid'] = $this->appid;
        $pars['out_batch_no'] = $this->out_batch_no;//商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
        $pars['batch_name']   = $this->batch_name;//该笔批量转账的名称
        $pars['batch_remark'] =  $this->batch_remark;//转账说明，，最多允许32个字符
        $pars['total_amount'] = $this->total_amount;//转账总金额 单位为“分”
        $pars['total_num']    = 1;//转账总笔数
        $pars['transfer_detail_list']  = [[
                                                'out_detail_no'=>'Dh'.$pars['out_batch_no'],
                                                'transfer_amount'=>$pars['total_amount'],
                                                'transfer_remark'=>$this->batch_name,
                                                'openid'=>$this->openid
                                        ]];//转账明细列表          
        $token  = $this->getToken($pars);//获取token
        $res    = $this->https_request($url,json_encode($pars),$token);//发送请求
        $resArr = json_decode($res,true);
 
        if(!empty($resArr["message"])){
            //file_get_contents("http://le.fuls.top/log/w?title=打款调试&data=".json_encode(  $resArr    )  );
            abort(202,$resArr['message']);
            //  return  returnmsg(202,$resArr['message']);
          // throw new HttpResponseException(returnmsg(202,$resArr['message']));
        }
        Db::name("user_tx")->where("id",$id)->update([
            'wx_txsn'=>$resArr['out_batch_no'],
            'is_dk'=>1
        ]);
        return returnmsg(200);
        //--
        //成功返回
        // array(3) {
        //   ["batch_id"] => string(40) "1030001016101247194272022062900873000000"
        //   ["create_time"] => string(25) "2022-06-29T10:21:30+08:00"
        //   ["out_batch_no"] => string(16) "sjzz202206291647001"
        // }
    }
    function https_request($url,$data = null,$token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function getToken($pars)
    {   
        // $url = 'https://api.mch.weixin.qq.com/v3/certificates';
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $http_method = 'POST';//请求方法（GET,POST,PUT）
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = json_encode((object)$pars);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
 
        $apiclient_cert_path = $this->apiclient_cert_path;
        $apiclient_key_path  = $this->apiclient_key_path;
        
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥
        $merchant_id = $this->merchant_id;//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
        $canonical_url."\n".
        $timestamp."\n".
        $nonce."\n".
        $body."\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $token;
    }
 
}
